#!/usr/bin/env python3
# _*_ coding: utf-8 _*_
# @Time : 2022/1/6 14:29
# @Author : zxiaosi
# @desc : 中间件
import time

from fastapi import FastAPI, Request, Response
from loguru import logger

from backend.service.monitor.oper_log import OperLogService


# 权限验证 https://www.cnblogs.com/mazhiyong/p/13433214.html
# 得到真实ip https://stackoverflow.com/questions/60098005/fastapi-starlette-get-client-real-ip
# nginx 解决跨域请求 https://segmentfault.com/a/1190000019227927
def register_middleware(app: FastAPI):
    """ 请求拦截与响应拦截 -- https://fastapi.tiangolo.com/tutorial/middleware/ """

    @app.middleware("http")
    async def logger_request(request: Request, call_next) -> Response:
        """
        请注意，这样的实现在响应流的主体不适合你的服务器内存时是有问题的（想象一下100GB的响应）。根据你的应用程序的作用，你将裁定这是否是一个问题。
        """
        # 返回性能计数器的值（以分秒为单位）
        start_time = time.perf_counter()
        response = await call_next(request)
        end_time = time.perf_counter()
        logger.debug(
            f"{response.status_code} {request.client.host} {request.method} {request.url} {end_time - start_time}s")
        return await OperLogService(request, response).log_oper()
